package com.zhx.sweet.authorize;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author zhx
 * @create 2017-12-18 9:39
 **/
@Component
public class ZhxAuthorizeConfigMananger implements AuthorizeConfigManager{

    /**
     * 将系统中实现了 AuthorizeConfigProvider 并且成功注册了spring容器bean的类全部自动加载进来
     */
    @Autowired
    private List<AuthorizeConfigProvider> authorizeConfigProviders;

    @Override
    public void config(ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry config) {
        boolean existAnyRequestConfig = false;
        String existAnyRequestConfigName = null;

        for(AuthorizeConfigProvider authorizeConfigProvider:authorizeConfigProviders){

            boolean currentIsAnyRequestConfig  = authorizeConfigProvider.config(config);

            if(existAnyRequestConfig && currentIsAnyRequestConfig){
                throw new RuntimeException("重复的anyRequest配置:" + existAnyRequestConfigName + "," + authorizeConfigProvider.getClass().getSimpleName());
            }else if (currentIsAnyRequestConfig) {
                existAnyRequestConfig = true;
                existAnyRequestConfigName = authorizeConfigProvider.getClass().getSimpleName();
            }
        }

        if(!existAnyRequestConfig){
            config.anyRequest().authenticated();
        }
    }
}
